<template>
  <div class="map-content">
    <div ref="map" class="map"></div>
    <div class="flex bm-control">
      <Select style="width: 100px" v-model="editType" @on-change="editTypeChange">
        <Option value="polylineDraw">折线选点</Option>
        <Option value="rectDraw">矩形选点</Option>
        <Option value="circleDraw">圆形选点</Option>
        <Option value="polygonDraw">多边形选点</Option>
      </Select>
      <Checkbox class="drawToggle" v-model="draw" @on-change="drawChange">开启绘制</Checkbox>
      <Button @click="handleSpeak">测试Web Speech API</Button>
    </div>
  </div>
</template>

<script>
import {DrawingType, DrawScene, OperateEventType, Select} from 'bmap-draw'

export default {
  data() {
    return {
      modalShow: false,
      loading: false,
      editType: 'polylineDraw',
      lastDrawType: 'polylineDraw',
      selectedOverlay: [],
      BMap: null,
      map: null,
      scene: null,
      rectDraw: null,
      circleDraw: null,
      polygonDraw: null,
      draw: false,
      polyLayer: null,
      synth: undefined,
      speech: undefined,
    }
  },
  mounted() {

    // setTimeout(() => {
    //   handleSpeakWithBaiduTts({
    //     tex: "请注意，游船A01发出报警信息"
    //   })
    //   this.$modal.alertWarning("请注意，游船A01发出报警信息！");
    // }, 5000)

    this.initMap()

    if (!window.SpeechSynthesisUtterance) {
      console.log("当前浏览器不支持文字转语音工具SpeechSynthesisUtterance，请使用其他浏览器！");
    } else {
      this.synth = window.speechSynthesis; // 启用文本
      setTimeout(() => {
        let voicesArr = window.speechSynthesis.getVoices();
        console.log("synth voicesArr: ", voicesArr);
      }, 2000);

      this.speech = new SpeechSynthesisUtterance(); // 表示一次发音请求。其中包含了将由语音服务朗读的内容，以及如何朗读它（例如：语种、音高、音量）。
    }
  },
  methods: {
    initMap() {
      const map = new BMapGL.Map(this.$refs.map)
      map.enableScrollWheelZoom(true)
      // map.centerAndZoom(new BMapGL.Point(116.291, 39.993), 13)
      this.map = map
      window.map = map
      const myCity = new BMapGL.LocalCity()
      myCity.get(result => {
        console.log(result)
        const cityName = result.name
        const point = new BMapGL.Point(result.center.lng, result.center.lat)
        // const marker = new BMapGL.Marker(point) // 创建标注
        // this.map.addOverlay(marker)
        this.map.centerAndZoom(point, 8)
        this.map.setCenter(cityName)
        this.initDraw()
        // this.addTestData()
      })
    },
    // 测试数据
    addTestData() {
      for (let i = 0; i < 500; i++) {
        let point = new BMapGL.Point(Math.random() * 40 + 85, Math.random() * 30 + 21)
        let marker = new BMapGL.Marker(point)
        this.polyLayer.addOverlay(marker.toGeoJSON())
        this.map.addOverlay(marker)
      }
    },
    drawChange(val) {
      const drawType = this.editType
      this.lastDrawType = drawType // 保存上一次绘制
      if (val) {
        this[drawType].openSelect()
      } else {
        this[drawType].closeSelect()
      }
    },
    editTypeChange(val) {
      this[this.lastDrawType].closeSelect()
      if (this.draw) {
        this[val].openSelect()
      }
    },
    initDraw() {
      const scene = new DrawScene(this.map)
      // 存储选择的元素
      this.selectedOverlay = []
      const polyLayer = new BMapGL.GeoJSONLayer('poly', {
        markerStyle: function (properties) {
          return {
            icon: new BMapGL.Icon(
              // require('./img/markers_red.png'),
              '/img/markers_red.png',
              new BMapGL.Size(21, 25),
              {
                anchor: new BMapGL.Size(10, 25)
              }
            )
          }
        }
      })
      this.map.addGeoJSONLayer(polyLayer)
      // const point = new BMapGL.Point(113.27143134, 23.13533631) //广州市坐标
      const point = new BMapGL.Point(114.31158155, 30.59846674) //武汉市坐标
      const marker = new BMapGL.Marker(point) // 创建标注
      // console.log("marker: ", marker)
      // console.log("marker.toGeoJSON(): ", marker.toGeoJSON())
      polyLayer.addOverlay(marker.toGeoJSON())

      polyLayer.addEventListener('click', (e) => {
        console.log("polyLayer click e: ", e)
        console.log(polyLayer.pickOverlays(e))
        if (e.features) { // 点击标注
          console.log(e)
        }
      })
      this.polyLayer = polyLayer
      // this.map.addOverlay(marker)
      console.log("polyLayer.overlayData: ", polyLayer.overlayData)
      scene.attachSnapSource(polyLayer.overlayData)
      this.scene = scene

      this.initMapDraw(scene, 'DRAWING_POLYLINE', 'polylineDraw') // 线选方法
      this.initMapDraw(scene, 'DRAWING_RECTANGLE', 'rectDraw') // 框选方法
      this.initMapDraw(scene, 'DRAWING_CIRCLE', 'circleDraw') // 圆选方法
      this.initMapDraw(scene, 'DRAWING_POLYGON', 'polygonDraw') // 多边形
    },
    // 初始化选择方法
    initMapDraw(scene, type, drawName) {
      const select = new Select(scene, {
        type: DrawingType[type],
        isSeries: true,
        isOnMap: true,
        skipEditing: true,
        enableSnap: true,
        graphicOpts: {
          fillColor: 'yellow'
        }
      })
      // 绘制方法
      const draw = {
        openSelect: () => {
          select.open()
          select.addEventListener(OperateEventType.COMPLETE, e => {
            console.log("select e: ", e);
            let overlay = e.target.overlay;
            console.log("select overlay: ", overlay);
            console.log("select overlay.getPath: ", overlay.getPath());
            // 选择计算
            // let result = GeoCalculator.intersect(this.polyLayer.overlayData, e.target.overlay.toGeoJSON())
            // this.polyLayer.resetStyle()
            // console.log("intersect result: ", result)
            // this.selectedOverlay = result || []
            // if (result instanceof Array) {
            //   result.forEach(item => {
            //     const activeStyle = { // 选中样式
            //       icon: new BMapGL.Icon(
            //         // require('./img/markers_blue2.png'),
            //         "/img/markers_blue2.png",
            //         new BMapGL.Size(21, 25),
            //         {
            //           anchor: new BMapGL.Size(10, 25)
            //         }
            //       )
            //     }
            //     item.setOptions(activeStyle)
            //   })
            // }
          })
        },
        closeSelect: () => {
          select.close()
          this.polyLayer.resetStyle()
          this.selectedOverlay = []
        }
      }
      this[drawName] = draw
    },

    handleSpeak() {
    },
    handleSpeakWithSpeechSynthesisUtterance(text) {
      console.log("handleSpeak text:", text)
      console.log("this.synth: ", this.synth);
      console.log("this.speech 1: ", this.speech);

      this.synth.cancel();

      setTimeout(() => {
        this.speech.text = text; // 文字内容: 测试内容
        this.speech.lang = "zh-CN"; // 使用的语言:中文
        this.speech.volume = 0.5; // 声音音量：1
        this.speech.rate = 1; // 语速：1
        this.speech.pitch = 1; // 音高：1
        let voicesArr = window.speechSynthesis.getVoices();
        console.log("voicesArr: ", voicesArr)
        let selectedVoice = voicesArr.filter(function (voice) {
          // return voice.localService == true && voice.lang == 'zh-CN'
          return voice.lang === 'zh-CN'
        })[0];
        console.log("selectedVoice: ", selectedVoice);
        this.speech.voice = selectedVoice;
        this.speech.onend = data => {
          console.log("speech播放结束，data: ", data)
        };
        this.speech.onerror = err => {
          console.log("speech播放出错，err: ", err)
        }

        console.log("this.speech 2: ", this.speech);
        this.synth.speak(this.speech); // 播放
      }, 1000)
    },

  }
}
</script>

<style>
.map-content {
  height: 100vh;
  width: 100vw;
  position: relative;
}

.map {
  height: 100%;
  width: 100%;
}

.bm-control {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 2000;
}

.drawToggle {
  height: 30px;
  background: #fff;
  margin-left: 10px;
  line-height: 30px;
  padding: 0 10px;
  border: 1px solid #d8dee5;
}

.bm-view {
  width: 100%;
  height: 100%;
}

.anchorBL {
  /* display: none; */
}
</style>
